package app.client;

import server.layer.Person;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;


public class ViewPanel extends JPanel {

    private static int NOT_FOUND_INDEX = -1;

    static ImagePanel imagePanel;
    private ArrayList<Person> persons = new ArrayList<Person>();
    private JTable table;
    private TextArea description;

    private JPanel buttonPanel;
    private JButton connButton;
    private JButton updateButton;
    private JButton addButton;
    private JButton deleteButton;
    private JButton addPicture;
    private JButton importFile;
    private JButton exportFile;

    static MyModel tableModel;

    private JFileChooser fileChooser;

    public ViewPanel() {

        tableModel = new MyModel(persons);
        table = new JTable(tableModel);
        table.setPreferredScrollableViewportSize(new Dimension(700, 300));
        table.setFillsViewportHeight(true);
        JScrollPane sclPane = new JScrollPane(table);
        add(sclPane, BorderLayout.WEST);
        imagePanel = new ImagePanel();
        imagePanel.setPreferredSize(new Dimension(300, 300));
        add(imagePanel, BorderLayout.EAST);
        imagePanel.setVisible(true);

        description = new TextArea();
        description.setEditable(false);

        add(description, BorderLayout.SOUTH);

        buttonPanel = new JPanel();
        add(buttonPanel, BorderLayout.SOUTH);

        connButton = new JButton("Connect Database");
        updateButton = new JButton("Update Database");
        addButton = new JButton("Add Person");
        deleteButton = new JButton("Delete Person");
        importFile = new JButton("Import File");
        exportFile = new JButton("Export File");
        addPicture = new JButton("Select Picture");
        importFile.setEnabled(false);
        exportFile.setEnabled(false);
        addPicture.setEnabled(false);

        buttonPanel.add(connButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(importFile);
        buttonPanel.add(exportFile);
        buttonPanel.add(addPicture);


        ListSelectionModel rowSelectionModel = table.getSelectionModel();
        rowSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


        rowSelectionModel.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (table.getSelectedRow() >= 0) {
                    Person p = persons.get(table.getSelectedRow());
                    int id = p.getId();
                    RequestSender.requestDescription(id);
                    description.setText(p.getDescription());
                    description.setEditable(true);
                    importFile.setEnabled(true);
                    exportFile.setEnabled(true);
                    addPicture.setEnabled(true);
                }
            }
        });


        description.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                if (table.getSelectedRow() != NOT_FOUND_INDEX) {
                    persons.get(table.getSelectedRow()).setDescription(description.getText());
                }
            }
        });


        connButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                RequestSender.connect();
            }
        });

        updateButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });

        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });


        importFile.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fileChooser = new JFileChooser();
                fileChooser.setCurrentDirectory(new File("."));
                int result = fileChooser.showOpenDialog(ViewPanel.this);

                if (result == JFileChooser.APPROVE_OPTION) {

                }
            }
        }

        );

        exportFile.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fileChooser = new JFileChooser();
                fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
                fileChooser.setSelectedFile(new File(persons.get(table.getSelectedRow()).getFileName()));

                int result = fileChooser.showSaveDialog(ViewPanel.this);

                if (result == JFileChooser.APPROVE_OPTION) {
                    try {
                        copyFile(new File(persons.get(table.getSelectedRow()).getFileName()), fileChooser.getSelectedFile());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }

        );

        addPicture.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fileChooser = new JFileChooser();
                fileChooser.setCurrentDirectory(new File("."));
                FileNameExtensionFilter fileFilter = new FileNameExtensionFilter("JPG files", "jpg");
                fileChooser.setFileFilter(fileFilter);
                fileChooser.setAccessory(new ImagePreviewer(fileChooser));
                int result = fileChooser.showOpenDialog(ViewPanel.this);

                if (result == JFileChooser.APPROVE_OPTION) {

                    try {
                        BufferedImage img = loadImage(fileChooser.getSelectedFile());
                        imagePanel.setImage(img);
                        ByteArrayOutputStream imageBuffer = new ByteArrayOutputStream();
                        ImageIO.write(img, "JPG", imageBuffer);
                        imageBuffer.flush();
                        imageBuffer.close();
                        byte[] image = imageBuffer.toByteArray();
                        RequestSender.sendNewImage(image, persons.get(table.getSelectedRow()).getId());

                        System.out.println("row = " + table.getSelectedRow() + "id = " + persons.get(table.getSelectedRow()).getId());

                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }


                }
            }
        }

        );

    }

    private BufferedImage loadImage(File image) throws IOException{
            BufferedImage img = ImageIO.read(image);
            return img;
    }

    private byte[] loadFile(File file) throws IOException {
        FileOutputStream fos = new FileOutputStream(file);
        byte[] byteFile = new byte[(int) file.length()];
        fos.write(byteFile);
        return byteFile;
    }

    private void saveFile(File file) throws IOException {

    }

    private void copyFile(File in, File out) throws Exception {
        FileInputStream fis = new FileInputStream(in);
        FileOutputStream fos = new FileOutputStream(out);
        byte[] buf = new byte[1024];
        int i = 0;

        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }

        fis.close();
        fos.close();
    }

}


